from app.models import Category, MerchantInfo
from django.core.exceptions import ValidationError
from middleware.util import make_response

class CategoryService:
    @staticmethod
    def create_category(merchant_id, category_name, sort_order=100):
        """
        创建一个新的菜品分类
        :param merchant_id: 商家 UUID
        :param category_name: 分类名称
        :param sort_order: 排序权重
        :return: JsonResponse 统一格式响应
        """
        try:
            merchant = MerchantInfo.objects.get(merchant_id=merchant_id)
        except MerchantInfo.DoesNotExist:
            return make_response(code=404, message="商家不存在")

        if Category.objects.filter(merchant=merchant, category_name=category_name).exists():
            return make_response(code=409, message="该商家已存在同名分类")

        category = Category.objects.create(
            merchant=merchant,
            category_name=category_name,
            sort_order=sort_order
        )

        return make_response(
            code=201,
            message="分类创建成功",
            data={
                "category_id": str(category.category_id),
                "category_name": category.category_name,
                "sort_order": category.sort_order
            }
        )

